<template>
  <div class="users">
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ name: 'Home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-form
      :model="searchForm"
      inline
      size="small"
      @submit.native="handleSearch"
    >
      <el-form-item>
        <el-input v-model="query">
          <el-button
            slot="append"
            icon="el-icon-search"
            @click="handleSearch"
          ></el-button>
        </el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleAdd">添加用户</el-button>
      </el-form-item>
    </el-form>
    <el-table v-loading="showLoading" :data="tableData" style="width: 100%">
      <el-table-column>
        <template slot-scope="{ $index }">{{ $index + 1 }}</template>
      </el-table-column>
      <el-table-column prop="username" label="用户名"> </el-table-column>
      <el-table-column prop="email" label="邮箱"> </el-table-column>
      <el-table-column prop="mobile" label="电话"> </el-table-column>
      <el-table-column label="创建日期">
        <template slot-scope="scope">
          {{ scope.row.create_time }}
        </template>
      </el-table-column>
      <el-table-column label="用户状态">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.mg_state"
            active-color="#13ce66"
            inactive-color="#ff4949"
            @change="(val) => changeUserState(val, scope.row)"
          >
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          {{ scope.$index }}
          <el-button
            type="primary"
            icon="el-icon-edit"
            size="small"
            circle
            @click="editUser(scope.row)"
          ></el-button>

          <el-popconfirm title="确定删除吗？" @confirm="delUser(scope.row.id)">
            <el-button
              type="info"
              icon="el-icon-delete"
              size="small"
              slot="reference"
              circle
            ></el-button>
          </el-popconfirm>
          <el-button
            type="success"
            icon="el-icon-check"
            size="small"
            @click="handleRole(scope.row)"
            circle
          ></el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="searchForm.pagenum"
      :page-sizes="[1, 2, 4, 8]"
      :page-size="searchForm.pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    >
    </el-pagination>
    <!-- <user-dialog
      @loginRequest="login"
      :rules="rules"
      :fileds="fileds"
      showLabel
      btnCon="注册"
    ></user-dialog> -->
    <user-dialog
      :rules="rules"
      :fileds="fileds"
      showLabel
      :visible.sync="dialogVisible"
      :title="title"
      :showBtn="false"
      @loginRequest="handleRequest"
    ></user-dialog>
    <el-dialog title="提示" :visible.sync="roleDialog" width="30%">
      <el-form :model="roleForm">
        <el-form-item label="用户名">
          <el-input
            v-model="roleForm.username"
            disabled
            placeholder="用户名"
          ></el-input>
        </el-form-item>
        <el-form-item label="角色">
          <el-select v-model="roleForm.rid" placeholder="活动区域">
            <el-option disabled :value="-1" label="请选择"></el-option>
            <el-option
              :key="item.id"
              v-for="item in roles"
              :label="item.roleName"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="roleDialog = false">取 消</el-button>
        <el-button type="primary" @click="distUserRole">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  getUsers,
  changeUserState,
  addUser,
  delUser,
  editUser,
  getRoleId,
  getRoles,
  distUserRole,
} from "@/http/api";
import UserDialog from "./UserDialog.vue";
export default {
  data() {
    return {
      query: "",
      searchForm: {
        query: "",
        pagesize: 4,
        pagenum: 1,
      },
      initSearchForm: {
        query: "",
        pagesize: 4,
        pagenum: 1,
      },
      tableData: [],
      total: 0,
      showLoading: false,
      //添加弹窗
      dialogVisible: false,
      //添加用户form
      // addForm: {
      //   username: "",
      //   password: "",
      //   email: "",
      //   mobile: "",
      // },
      addFileds: [
        {
          prop: "username",
          type: "text",
          label: "用户名",
          placeholder: "请输入用户名",
        },
        {
          prop: "password",
          type: "password",
          label: "密码",
          placeholder: "请输入密码",
        },
        {
          prop: "email",
          type: "email",
          label: "邮箱",
          placeholder: "请输入邮箱",
        },
        {
          prop: "mobile",
          type: "tel",
          label: "电话",
          placeholder: "请输入电话号",
        },
      ],
      addFormRules: {
        username: [
          {
            required: true,
            message: "请输入用户名",
            trigger: ["blur", "change"],
          },
        ],
        password: [
          {
            required: true,
            message: "请输入密码",
            trigger: ["blur", "change"],
          },
        ],
        email: [],
        mobile: [],
      },
      title: "",
      rules: {},
      fileds: {},
      handleName: "",
      userId: null,
      roleDialog: false,
      roleForm: {},
      roles: [],
    };
  },
  components: {
    UserDialog,
  },
  methods: {
    handleSizeChange(val) {
      this.searchForm.pagesize = val;
      this.handleSearch();
      console.log(`每页 ${val} 条`);
    },
    handleCurrentChange(val) {
      this.searchForm.pagenum = val;
      this.handleSearch();
      console.log(`当前页: ${val}`);
    },
    //获取用户列表
    async getUsers() {
      this.showLoading = true;
      const res = await getUsers(this.searchForm);
      this.tableData = res.users;
      this.total = res.total;
      this.showLoading = false;
      console.log(res);
    },
    //搜索用户列表
    handleSearch(e) {
      e && (this.searchForm.query = this.query);
      e && (this.searchForm.pagenum = 1);
      this.getUsers();
      e && e.preventDefault();
    },
    //改变用户状态
    async changeUserState(val, row) {
      await changeUserState({ uId: row.id, type: val });
    },
    //添加用户弹窗
    handleAdd() {
      this.dialogVisible = true;
      this.title = "新增用户";
      this.handleName = "handleUserAdd";
      this.rules = this.addFormRules;
      this.fileds = [...this.addFileds];
    },
    //编辑用户弹窗
    editUser(obj) {
      this.dialogVisible = true;
      this.title = "编辑用户";
      this.handleName = "handleUserEdit";
      this.rules = this.addFormRules;
      this.userId = obj.id;
      this.fileds = [...this.addFileds];
      this.fileds.splice(1, 1);
      this.fileds.forEach((item, index) => {
        // this.$set(this.fileds[index], `value`, obj[item.prop]);
        if (item.prop === "username") {
          this.$set(this.fileds, index, {
            ...item,
            value: obj[item.prop],
            disabled: true,
          });
        } else {
          this.$set(this.fileds, index, { ...item, value: obj[item.prop] });
        }
        // item.value = obj[item.prop];
      });
    },
    //编辑用户
    async handleUserEdit(val) {
      console.log(val);
      await editUser({ ...val, id: this.userId });
      this.dialogVisible = false;
      this.searchForm = Object.assign({}, this.initSearchForm);
      this.getUsers();
    },
    //添加用户确认按钮事件
    async handleUserAdd(val) {
      await addUser(val);
      this.dialogVisible = false;
      this.searchForm = Object.assign({}, this.initSearchForm);
      this.getUsers();
    },

    //删除用户
    async delUser(id) {
      await delUser(id);
      this.searchForm = Object.assign({}, this.initSearchForm);
      this.getUsers();
    },
    handleRequest(val) {
      console.log("校验通过");
      this[this.handleName](val);
    },
    //分配角色弹窗
    async handleRole(val) {
      this.roleForm = val;
      const role = await this.getRoleId(val.id);
      const roles = await this.getRoles();
      this.$set(this.roleForm, "rid", role.rid);
      this.roles = roles;
      this.roleDialog = true;
    },
    //查询用户角色id
    async getRoleId(id) {
      return await getRoleId(id);
    },
    //获取所有角色
    async getRoles() {
      return await getRoles();
    },
    //分配用户角色
    async distUserRole() {
      await distUserRole({ id: this.roleForm.id, rid: this.roleForm.rid });
      this.roleDialog = false;
      this.searchForm = Object.assign({}, this.initSearchForm);
      this.getUsers();
    },
  },
  created() {
    this.getUsers();
  },
};
</script>

<style></style>
